﻿using System;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace Nextensions.GUI
{
    public partial class IpInput : UserControl
    {
        private static readonly Regex _validIp = new Regex(@"(?<1>\d{1,3})\.(?<2>\d{1,3})\.(?<3>\d{1,3})\.(?<4>\d{1,3})");

        public IpInput()
        {
            InitializeComponent();
        }

        public string Ip
        {
            get
            {
                return String.Format("{0}.{1}.{2}.{3}", tAccIp1.Text, tAccIp2.Text, tAccIp3.Text, tAccIp4.Text);
            }
            set
            {
                if (value == null || value.Trim() == "")
                {
                    tAccIp1.Text = "";
                    tAccIp2.Text = "";
                    tAccIp3.Text = "";
                    tAccIp4.Text = "";
                    return;
                }

                Match ip = _validIp.Match(value);
                
                if (!ip.Success)
                    return;

                tAccIp1.Text = ip.Groups["1"].Value;
                tAccIp2.Text = ip.Groups["2"].Value;
                tAccIp3.Text = ip.Groups["3"].Value;
                tAccIp4.Text = ip.Groups["4"].Value;
            }
        }

        public bool AddressIsValid
        {
            get
            {
                return _validIp.IsMatch(Ip);
            }
        }

        private void tAccIp_TextChanged(object sender, System.EventArgs e)
        {
            TextBox ipTextbox = (TextBox)sender;
            Match tbox = Regex.Match(ipTextbox.Name, @"(?<prefix>\D+)(?<num>\d+)$");
            int index = Int32.Parse(tbox.Groups["num"].Value);

            if(index == 4 || ipTextbox.Text.Length < 3)
                return;

            index = Controls.IndexOfKey(String.Format("{0}{1}", tbox.Groups["prefix"].Value, ++index));

            Controls[index].Focus();
        }

        public override string Text
        {
            get
            {
                return Ip;
            }
            set
            {
                Ip = value;
            }
        }
    }
}
